package at.technikum.fotoalbum.phaselistener;

import java.io.IOException;

import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import at.technikum.fotoalbum.beans.SessionBean;

public class AccessPhaseListener implements PhaseListener {

    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
 
    public void beforePhase(PhaseEvent event) {
    }
 
    public void afterPhase(PhaseEvent event) {
        FacesContext fc = event.getFacesContext();
        ExternalContext extContext = fc.getExternalContext();
        NavigationHandler nh = fc.getApplication().getNavigationHandler();
        
        SessionBean sb = (SessionBean) fc.getCurrentInstance().getExternalContext()
        .getSessionMap().get( "sessionBean");
        // Check to see if they are on the login page.
        String page = fc.getViewRoot().getViewId();
        if (sb != null) {
        	if (!sb.getIsAdmin()) {
        		if (page.equals("/pages/adminUserList.xhtml")) {
    				this.redirectToMainpage(extContext);
    				//context.renderResponse();
    				fc.responseComplete();
            	}
        		
        		if (page.equals("/pages/adminUserDetail.xhtml")) {
    				this.redirectToMainpage(extContext);
    				//context.renderResponse();
    				fc.responseComplete();
            	}
        		
        	}
        	
        	if (!sb.isLoggedIn()) {
        		if (page.equals("/pages/userHome.xhtml")) {
    				this.redirectToMainpage(extContext);
    				//context.renderResponse();
    				fc.responseComplete();
            	}
        		if (page.equals("/pages/userPictureUpload.xhtml")) {
    				this.redirectToMainpage(extContext);
    				//context.renderResponse();
    				fc.responseComplete();
            	}
        		if (page.equals("/pages/userSettings.xhtml")) {
    				this.redirectToMainpage(extContext);
    				//context.renderResponse();
    				fc.responseComplete();
            	}
        		
        	}
        } else {
        	if (page.equals("/pages/adminUserList.xhtml") ||
        			page.equals("/pages/adminUserDetail.xhtml") ||
        			page.equals("/pages/userHome.xhtml") ||
        			page.equals("/pages/userPictureUpload.xhtml") ||
        			page.equals("/pages/imageDetail.xhtml") ||
        			page.equals("/pages/userSettings.xhtml")
        			) {
				this.redirectToMainpage(extContext);
				//context.renderResponse();
				fc.responseComplete();
        	}
        	
        }
        
    }
 
	private void redirectToMainpage(ExternalContext extContext) {
		try {
			extContext.redirect(extContext.encodeActionURL("/bilderalbum/pages/mainpage.xhtml"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}